package com.ruoyi.project.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.project.pay.domain.PayConfig;
import com.ruoyi.project.pay.service.IPayConfigService;
import com.ruoyi.tools.pay.domain.WxPayBean;
import com.ruoyi.tools.util.http.HttpPostUtil;
import com.ruoyi.tools.wechat.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.RegisterBody;
import com.ruoyi.framework.security.service.SysRegisterService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.service.ISysConfigService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 注册验证
 * 
 * @author ruoyi
 */
@RestController
public class SysRegisterController extends BaseController
{
    @Autowired
    private IPayConfigService payConfigService;

    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private WxPayBean wxPayBean;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user)
    {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
        {
            return error("当前系统没有开启注册功能！");
        }
        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    /**
     * 小程序
     * code 换取手机号
     */
    @RequestMapping("/getPhone")
    @ResponseBody
    public AjaxResult getPhone(@RequestParam String code) {
        if (!("true".equals(configService.selectConfigByKey("wx.account.registerUser"))))
        {
            return error("当前系统没有开启小程序注册功能！");
        }

        //1.获取小程序传过来的code
        System.out.println("code:"+code);
        String access_token = tokenUtil.GetAccess_Token();
        System.out.println("access_token:"+access_token);
        // 2.请求微信接口服务，获取用户手机号信息
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
        JSONObject body = new JSONObject();
        body.put("code", code);
        System.out.println("body:"+body);
        String phone = "";
        try {
            String ret = HttpPostUtil.httpPostRaw(url, body.toString(), null, null);
            System.out.println("ret:"+ret);
            if(ret != null && !"".equals(ret)) {
                JSONObject json = JSONObject.parseObject(ret);
                System.out.println("json:"+json);
                JSONObject phone_info = json.getJSONObject("phone_info");
                System.out.println("phone_info:"+phone_info);
                phone = phone_info.getString("phoneNumber");
                System.out.println(phone);

                return AjaxResult.success(phone);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.error("获取手机号失败");
    }

    /**
     * 小程序
     * @param user 授权信息
     * @return token
     */
    @PostMapping("/wxLogin")
    public AjaxResult wxLogin(@RequestBody RegisterBody user)
    {
        if (!("true".equals(configService.selectConfigByKey("wx.account.registerUser"))))
        {
            return error("当前系统没有开启小程序注册功能！");
        }
        AjaxResult msg = registerService.wxLogin(user);
        return msg;
    }

    /**
     * 公众号
     * 授权登录
     */
    @RequestMapping("/oauth")
    public void oauth(HttpServletResponse response, @RequestParam(value = "inviterId") String inviterId) throws IOException {

        PayConfig payConfig = new PayConfig();
        payConfig.setName("wechatPay");
        List<PayConfig> payConfigs = payConfigService.selectPayConfigList(payConfig);
        PayConfig pConfig = payConfigs.get(0);

        //	项目服务器url
        String path = pConfig.getNotifyPayDomain()+"/invoke?inviterId="+inviterId;
        try {
            path = URLEncoder.encode(path, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //   &redirect_uri=https://3v60q97798.zicp.fun/wechat/wcuser/api/invoke?inviterId=
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + pConfig.getAppid() +
                "&redirect_uri=" + path +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=comi" +
                "#wechat_redirect";

        System.out.println("链接\n"+url);
        response.sendRedirect(url);
    }

    /**
     * 公众号
     * 第二步：用户同意授权，页面跳转至/invoke
     * 非静默
     */
    @RequestMapping("/invoke")
    @ResponseBody
    public AjaxResult invoke(@RequestBody RegisterBody user){
        System.out.println("user" + user);

        //校验code
        if(StringUtils.isEmpty(user.getCode())){
            return AjaxResult.error("code校验失败");
        }

        Map<String, Object> map = registerService.loginNoSilent(user);
        System.out.println(map);

        return AjaxResult.success(map);
    }



}
